<template>
  <!-- 在vue项目中使用腾讯地图 -->
  <div class="mapContainer" v-loading="mapLoading">
    <tx-map ref="map" id="map" class="container" />
  </div>
</template>

<script>
import Vue from "vue";
import TxMap from "@/components/TxMap"; //腾讯地图
import mapInfowindowPane from "./components/mapInfowindowPane";
export default {
  components: { TxMap },
  data() {
    return {
      mapData: {
        latitude: "23.16584388345954",
        longitude: "113.36079213212736",
        max_distance: "5000",
        poiname: "广州体育职业技术学院",
      },
      //模拟后端返回的数据
      mapArray: [
        {
          amount: 0.1,
          count: 1,
          distance: "1.1 km",
          id: 122817,
          latitude: "23.150952",
          longitude: "113.34669",
          order_info: [
            {
              bank_type: "其他",
              bank_type_id: 3,
              level_name: "1号营业所",
              merchant_name: "小李",
              money: 50,
              pay_time: "2023-07-28 13:24:37",
            },
            {
              bank_type: "建设银行",
              bank_type_id: 1,
              level_name: "1号营业所",
              merchant_name: "老张",
              money: 18.88,
              pay_time: "2023-07-28 13:24:37",
            },
          ],
        },
        {
          amount: 0.1,
          count: 1,
          distance: "1.1 km",
          id: 122817,
          latitude: "23.170952",
          longitude: "113.35669",
          order_info: [
            {
              bank_type: "其他",
              bank_type_id: 3,
              level_name: "1号营业所",
              merchant_name: "小李",
              money: 50,
              pay_time: "2023-07-28 13:24:37",
            },
          ],
        },
      ],
      map: "",
      infoWindow: "",
      mapLoading: false,
    };
  },
  methods: {
    // 地址搜索事件
    loadMap() {
      this.mapLoading = true;
      // 地址转坐标
      let map_key = "5PLBZ-KIZC6-NCKSH-MOPXS-QP6OK-M4BIO"; //腾讯地图key
      this.$jsonp(
        `https://map.qq.com/api/gljs?v=1.exp&key=${map_key}&address=${this.mapData.poiname}`
      )
        .then((res) => {
          /**
           * 已加载的信息窗体，重新定位后不会关闭，
           * 所以需要销毁地图重新绘制地图再渲染对应的信息窗体数据
           */
          if (this.map) {
            this.map.destroy(); //销毁地图
          }

          //设置地图的中心点坐标
          let center = new TMap.LatLng(
            this.mapData.latitude,
            this.mapData.longitude
          );

          //初始化地图
          this.map = new TMap.Map("container", {
            center: center,
            zoom: 14,
          });

          //初始化marker图层
          var markerLayer;
          markerLayer =  markerLayer = this.setMarkerLayer();
          //初始化地图的设中心点坐标
          markerLayer.add({
            position: center,
          });

          /**
           * 监听点击事件添加marker
           * 只保留一个marker
           * 定位改变后重新绘制地图，重新定位地图的中心点经纬度
           */
          this.map.on("click", (evt) => {
            console.log("evt", evt);
            console.log("this.infoWindow", this.infoWindow);
            //this.map.destroy();
            this.loadMap();
            this.mapData.latitude = evt.latLng.lat;
            this.mapData.longitude = evt.latLng.lng;
            /**
             * 判断地图定位是否已存在
             * 已存在：清空再添加
             * 不存在：直接添加
             */
            if (markerLayer) {
              markerLayer.setMap(null); //清空已存在的定位
              markerLayer = this.setMarkerLayer();
              markerLayer.add({
                position: evt.latLng,
              });
            } else {
              markerLayer.add({
                position: evt.latLng,
              });
            }
          });

          // 地图比例尺改变事件
          this.map.on("zoom_changed", () => {
            var zoom = this.map.getZoom();
            console.log("缩放", zoom);
            console.log("标尺", this.map.getScale());
          });

          //在地图上定位地点
          this.init();
        })
        .finally(() => {
          this.mapLoading = false;
        });
    },

    //初始化中心标点定位参数
    setMarkerLayer() {
      return new TMap.MultiMarker({
        id: "marker-layer",
        map: this.map,
        styles: {
          marker: new TMap.MarkerStyle({
            width: 20, // 样式宽
            height: 30, // 样式高
            anchor: { x: 10, y: 30 }, // 描点位置
            src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png",
          }),
        },
      });
    },

    init() {
      this.mapPointArray = [];
      if (this.mapArray && this.mapArray.length > 0) {
        this.mapArray.forEach((item1) => {
          item1.order_info.forEach((item, index) => {
            console.log("item", item);
            console.log("index", index);
            let xPosition =
                (item1.order_info.length - 1) * 4 - index * 4,
              yPosition = -(
                32 +
                (item1.order_info.length - 1) * 4 -
                index * 4
              );

            this.mapPointArray.push({
              styleId: "marker",
              position: new TMap.LatLng(
                item1.latitude,
                item1.longitude
              ), // 点标记的坐标位置
              amount: item.money,
              time: item.pay_time,
              merchant: item.merchant_name,
              pay_way: item.bank_type_id,
              pay_way_str: item.bank_type,
              x: xPosition,
              y: yPosition,
              latitude: item1.latitude,
              longitude: item1.longitude,
              distance: item1.distance,
            });
          });
        });
      } else {
        this.mapPointArray = [];
      }

      //初始化marker
      var marker = new TMap.MultiMarker({
        map: this.map,
        styles: {
          marker: new TMap.MarkerStyle({
            width: 20, // 样式宽
            height: 30, // 样式高
            anchor: { x: 10, y: 30 }, // 描点位置
            //src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png",
          }),
        },
        enableCollision: true, // 开启碰撞
        geometries: this.mapPointArray, //多个信息窗口
      });

      //初始化infoWindow
      this.mapPointArray.forEach((item) => {
        this.setInfoWindowContent(item, this.map);
        this.infoWindow.open(); //打开信息窗
        this.infoWindow.setPosition(item.position); //设置信息窗位置
      });
    },

    //将vue组件传入腾讯地图信息窗体infoWindow中
    setInfoWindowContent(data, map) {
      let Content = Vue.extend({
        //自定义模板继承
        template: `<mapInfowindowPane
          ref="infoWindowPart"
          :infowindowData="mapArray"
        ></mapInfowindowPane>`,
        components: {
          mapInfowindowPane, //弹框组件
        },
        data() {
          return {
            mapArray: data,
          };
        },
      });
      let component = new Content().$mount(); //手动挂载组件
      console.log("data", data);
      this.infoWindow = new TMap.InfoWindow({
        map: map,
        position: data.position, //信息窗体的经纬度
        offset: {
          x: data.x ? data.x : 0,
          y: data.y ? data.y : -32,
        }, //设置信息窗相对position偏移像素
        content: component.$el.outerHTML,
        enableCustom: true, //是否自定义信息窗体（默认为false：就是使用腾讯地图自带的信息窗体样式）
      });
    },
  },
  mounted() {
    this.loadMap();
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 800px;
  display: inline-block;
  // 容器可拖放
  resize: both;
  overflow: auto;
}

.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 99999999999;
  position: fixed; //关键样式设置固定定位
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
}

.contextmenu li {
  margin: 0;
  padding: 7px 16px;
  cursor: pointer;
}
.contextmenu li:hover {
  background: #eee;
}
</style>
